
import os
from flask import request, jsonify
from flask import Blueprint, request, jsonify
from werkzeug.utils import secure_filename
import datetime
from framework.prompt.DocLoader import docloaders, regist_docloader
from tool.config import config as tool_config
from tool.auth.cookieCheck import cookie_jwt_required

config = tool_config.get_config("config.toml")
fs_bp = Blueprint('filesys', __name__)

@fs_bp.route("/api/files", methods=["GET"])
@cookie_jwt_required
def list_files():
    path = request.args.get("path", "")
    user_root = os.path.join(config["FILE_SYSTEM"]["UPLOAD_FOLDER"], request.user["user"])
    target_path = os.path.normpath(os.path.join(user_root, path.lstrip("/")))
    if not os.path.exists(target_path):
        return jsonify({"error": "路径不存在"}), 404
    files = []
    # 添加上一级入口（除根目录）
    if os.path.normpath(target_path) != os.path.normpath(user_root):
        parent_path = os.path.relpath(os.path.join(target_path, ".."), user_root)
        files.append({
            "name": "..",
            "isDirectory": True,
            "size": 0,
            "modified": "",
            "path": parent_path.replace("\\", "/")
        })
    for item in os.listdir(target_path):
        item_path = os.path.join(target_path, item)
        is_dir = os.path.isdir(item_path)
        size = os.path.getsize(item_path) if not is_dir else 0
        modified = datetime.fromtimestamp(os.path.getmtime(item_path))
        rel_path = os.path.relpath(item_path, user_root).replace("\\", "/")
        files.append({
            "name": item,
            "isDirectory": is_dir,
            "size": size,
            "modified": modified.isoformat(),
            "path": rel_path
        })
    return jsonify(files), 200

@fs_bp.route("/api/folder", methods=["POST"])
@cookie_jwt_required
def create_folder():
    data = request.get_json()
    path = data.get("path", "")
    name = data.get("name")
    if not name:
        return jsonify({"error": "文件夹名称不能为空"}), 400
    user_root = os.path.join(config["FILE_SYSTEM"]["UPLOAD_FOLDER"],request.user["user"])
    target_path = os.path.normpath(os.path.join(user_root, path.lstrip("/"), name))
    print(f"target_path:{target_path}")
    if os.path.exists(target_path):
        return jsonify({"error": "文件夹已存在"}), 409

    os.makedirs(target_path)
    return jsonify({"message": "文件夹创建成功"}), 201

@fs_bp.route("/api/upload", methods=["POST"])
@cookie_jwt_required
def upload_file():
    path = request.form.get("path", "")
    doctype = request.form.get("file_type")
    if "files" not in request.files:
        return jsonify({"error": "没有上传文件"}), 400
    files = request.files.getlist("files")
    uploaded_files = []
    user_root = os.path.join(config["FILE_SYSTEM"]["UPLOAD_FOLDER"], request.user["user"])
    target_path = os.path.normpath(os.path.join(user_root, path.lstrip("/")))
    os.makedirs(target_path, exist_ok=True)
    for file in files:
        if file.filename == "":
            return jsonify({"error": "文件名不能为空"}), 400
        filename = secure_filename(file.filename)
        file_path = os.path.join(target_path, filename)
        counter = 1
        base, ext = os.path.splitext(filename)
        while os.path.exists(file_path):
            filename = f"{base}_{counter}{ext}"
            file_path = os.path.join(target_path, filename)
            counter += 1
        file.save(file_path)
        uploaded_files.append(filename)
    regist_docloader(request.user["user"])
    # vec = DocLoader(persist_directory=user_vec_db, embeddings_model=local_embeddings)
    docloaders[request.user["user"]].add_documents_to_vectorstore(file_path,doctype)
    return jsonify({
        "message": f"{len(uploaded_files)}个文件上传成功",
        "filenames": uploaded_files
    }), 201

@fs_bp.route("/api/delete", methods=["POST"])
@cookie_jwt_required
def delete_item():
    data = request.get_json()
    path = data.get("path")
    if not path:
        return jsonify({"error": "路径不能为空"}), 400
    user_root = os.path.join(config["FILE_SYSTEM"]["UPLOAD_FOLDER"],request.user["user"])
    target_path = os.path.normpath(os.path.join(user_root, path.lstrip("/")))
    if not os.path.exists(target_path):
        return jsonify({"error": "路径不存在"}), 404
    if os.path.isdir(target_path):
        if os.listdir(target_path):
            return jsonify({"error": "文件夹不为空，无法删除"}), 400
        os.rmdir(target_path)
    else:
        regist_docloader(request.user["user"])
        # vec = DocLoader(persist_directory=user_vec_db, embeddings_model=local_embeddings)
        docloaders[request.user["user"]].delete_documents_by_file(target_path)
        os.remove(target_path)
    return jsonify({"message": "删除成功"}), 200

@fs_bp.route("/api/rename", methods=["PUT"])
@cookie_jwt_required
def rename_item():
    data = request.get_json()
    path = data.get("path")
    new_name = data.get("newName")
    if not path or not new_name:
        return jsonify({"error": "路径和新名称不能为空"}), 400
    user_root = os.path.join(config["FILE_SYSTEM"]["UPLOAD_FOLDER"], request.user["user"])
    target_path = os.path.normpath(os.path.join(user_root, path.lstrip("/")))
    dir_path, old_name = os.path.split(target_path)
    new_path = os.path.join(dir_path, secure_filename(new_name))
    if not os.path.exists(target_path):
        return jsonify({"error": "路径不存在"}), 404
    if os.path.exists(new_path):
        return jsonify({"error": "新名称的文件/文件夹已存在"}), 409
    os.rename(target_path, new_path)
    return jsonify({"message": "重命名成功"}), 200